package topsun.rms.services;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Hibernate;
import org.springframework.stereotype.Service;

import topsun.framework.utility.HqlFilter;
import topsun.rms.dao.IBaseDao;
import topsun.rms.entity.UserRole;

/**
 * 资源服务实现
 * 
 * @author yuxiaobei
 *
 */
@Service("resourceService")
public class ResourceService extends BaseService<topsun.rms.entity.Resource> implements IResourceService
{
	@Resource(name = "resourceDao")  
	public void setDao(IBaseDao<topsun.rms.entity.Resource> dao) 
	{  
		super.setDao(dao);  
	}

	@Override
	public List<topsun.rms.entity.Resource> getMainMenu(HqlFilter hqlFilter) 
	{
		List<topsun.rms.entity.Resource> l = new ArrayList<topsun.rms.entity.Resource>();
		
		String hql = "select distinct t from Resource t join t.userroles role join role.users user";
		List<topsun.rms.entity.Resource> resource_role = find(hql + hqlFilter.getWhereHql(), hqlFilter.getParams());
		
		l.addAll(resource_role);
		
		hql = "select distinct t from Resource t join t.userroles role join role.usergroups usergroup join usergroup.users user ";
		List<topsun.rms.entity.Resource> resource_grouprole = find(hql + hqlFilter.getWhereHql(), hqlFilter.getParams());
		l.addAll(resource_grouprole);
		
		l = new ArrayList<topsun.rms.entity.Resource>(new HashSet<topsun.rms.entity.Resource>(l));// 去重
	
		Collections.sort(l, new Comparator<topsun.rms.entity.Resource>() 
				{// 排序
					@Override
					public int compare(topsun.rms.entity.Resource o1, topsun.rms.entity.Resource o2) {
						if (o1.getSortno() == null) {
							o1.setSortno(1000L);
						}
						if (o2.getSortno() == null) {
							o2.setSortno(1000L);
						}
						return o1.getSortno().compareTo(o2.getSortno());
					}
				});
		return l;
	}
	
	@Override
	public List<topsun.rms.entity.Resource> getMenu(HqlFilter hqlFilter) 
	{
		List<topsun.rms.entity.Resource> l = new ArrayList<topsun.rms.entity.Resource>();
		
		String hql = "select distinct t from Resource t ";
		List<topsun.rms.entity.Resource> resource_role = find(hql + hqlFilter.getWhereAndOrderHql() , hqlFilter.getParams());
		l.addAll(resource_role);
		return l;
	}

	@Override
	public List<topsun.rms.entity.Resource> findResByFilter(HqlFilter hqlFilter)
	{
		String hql = "select distinct t from Resource t join t.userroles role";
		return find(hql + hqlFilter.getWhereAndOrderHql(), hqlFilter.getParams());
	}
	
	/**
	 * 解决更新删除关联问题
	 */
	@Override
	public void update(topsun.rms.entity.Resource resource)
	{
		topsun.rms.entity.Resource tresource = getById(resource.getId());
		Hibernate.initialize(tresource.getUserroles());
		resource.setUserroles(tresource.getUserroles());
		
		super.merge(resource);
	}
}
